package net.wenku8.reader.view.user

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.UserApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.model.user.UserInfo
import net.wenku8.reader.state.StateLogin
import net.wenku8.reader.view.common.BaseViewModel

class UserViewModel : BaseViewModel() {
    var userInfo by mutableStateOf(UserInfo())

    fun initData() {
        if (!StateLogin.status.value){
            return
        }
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = UserApi.getUserInfo()
            if (ApiResult.isSuccess(apiResult)){
                userInfo = apiResult.data!!
            }
        }
    }

    fun onLogout(){
        if (!StateLogin.status.value){
            return
        }
        viewModelScope.launch(Dispatchers.IO){
            val apiResult = UserApi.logout()
            if (ApiResult.isSuccess(apiResult)){
                userInfo = UserInfo()
            }
        }
    }

    fun userSign(){
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = UserApi.doUserSign()
            if (ApiResult.isSuccess(apiResult)){
                showSnackbar("签到成功")
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }
}